//
//  NavBarAppDelegate.m
//  NavBar
//
//  Created by Thiago on 23/07/2009.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "NavBarAppDelegate.h"

@implementation NavBarAppDelegate

@synthesize window, mainController, myWebView, userPrefences, actionDescrArray, actionURLArray;
@synthesize isAVLoaded, statValArray, statAttrArray, sectionContents, prefController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {  
	
	isAVLoaded = 0;
	actionDescrArray = [[NSMutableArray alloc] init];
	actionURLArray = [[NSMutableArray alloc] init];
	statValArray = [[NSMutableArray alloc] init];
	statAttrArray = [[NSMutableArray alloc] init];
	
	myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
	
	//Expose mainController to Webview's JavaScript
	myWebView.delegate = self;	
	
	self.mainController = [[NavBarViewController alloc] init];
	UINavigationController *navController = [UINavigationController alloc];
	
	if ( [self loadPreferences]) {
	
		//Navigation controller for the NavBar
		 [navController initWithRootViewController:mainController];

		
	} else {
		
		self.prefController = [[UserPreferencesViewController alloc] init];
		
		//Navigation controller for the preferences
		[navController initWithRootViewController:prefController];		
	}	
	
	[navController setNavigationBarHidden:YES];
	
	CGRect screenBounds = [[UIScreen mainScreen] bounds];
	self.window = [[[ UIWindow alloc] initWithFrame: screenBounds] autorelease];
	
	// add the navigation controller's view to the window
    [window addSubview:navController.view];
    [window makeKeyAndVisible];


}

- (BOOL)loadPreferences {
	// Load user preferences. If they are not set, use shackbbs.com as the default site.
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	if ( [prefs objectForKey:@"userBaseURL"] != nil ){
		
		if ( [prefs objectForKey:@"userName"] != nil && [prefs objectForKey:@"userPass"] != nil ) {
			// NSLog(@"here");
			userPrefences = [[NSArray alloc] initWithObjects:[prefs objectForKey:@"userBaseURL"], [prefs objectForKey:@"userName"], [prefs objectForKey:@"userPass"], nil];
		} else {
			// NSLog(@"empty user");
			userPrefences = [[NSArray alloc] initWithObjects:[prefs objectForKey:@"userBaseURL"], nil];
		}
		return true;
	}else{
		return false;
	}
}	

- (void)dealloc {
	[mainController release];
    [window release];
    [super dealloc];
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
	NSURL *url = request.URL;
	NSString *urlString = url.absoluteString;
	// NSLog(@"Requested URL: %@", urlString);
	if(navigationType == UIWebViewNavigationTypeOther){
		return YES;
	}else if(navigationType == UIWebViewNavigationTypeFormSubmitted){
		[mainController processRequest:request];
		return NO;
	}else{
		[mainController processURL:url];
		return NO;
	}
}



@end
